//
//  FormView.swift
//  ZYA
//
//  Created by 邱仙凯 on 2025/4/1.
//  Copyright © 2025 zwb. All rights reserved.
//
enum KSRoundType { // 顶部圆角   底部圆角  都圆角  都不圆角
    case top,bottom,all,never
}
let titleColorLightGray = UIColor(kshex:"888888")

class FormView:UIView {
    var tail: FormItem?
    var head: FormItem?
    
    func reFrame(item:FormItem) {
  
        if item.nextV.isSome {
            if item.isKind(of: KSFormBaseItem.self) {
                let item_f = item as! KSFormBaseItem
                let hhh = getHeightFromItem(item:item,appearance: item_f.appearance, type: item_f.getNowType())
                 item.ks_height = hhh
            }
            item.nextV!.ks_y = item.frame.maxY
            reFrame(item: item.nextV!)
        } else {
            if item.isKind(of: KSFormBaseItem.self) {
                let item_f = item as! KSFormBaseItem
                let hhh = getHeightFromItem(item:item,appearance: item_f.appearance, type: item_f.getNowType())
                item.ks_height = hhh
            }
            self.ks_height = item.frame.maxY
        }
    }
  
    
    func insertx(_ item:FormItem,preItem:FormItem,success:(()->())) {
        
        if let tempItem = item as? KSFormHItem {
            let hhh = getHeightFromItem(item:item,appearance: tempItem.appearance, type: tempItem.getNowType())
            item.frame = CGRect(x: 0, y:preItem.frame.maxY, width: self.ks_width, height: hhh)
            self.addSubview(item)
        } else {
            item.frame = CGRect(x: 0, y:preItem.frame.maxY, width: self.ks_width, height: ItemBtnHeight)
            self.addSubview(item)
        }
        if self.tail == preItem {
            self.tail = item
        }
        
        KSLog("在\(preItem.tagx.unwrap)后面插入\(item.tagx.unwrap)---------")
         item.nextV = preItem.nextV
        preItem.nextV = item
        
        reFrame(item: preItem)
        
        
        success()
    }
 
    // 替换控件
    func switchx(_ item:KSFormHItem,oriItem:FormItem,success:(()->())) {
        self.addSubview(item)
        for subV in self.subviews {
            if subV.isKind(of: FormItem.self) {
                let sss:FormItem = subV as! FormItem
                if sss.nextV == oriItem {
                    sss.nextV = item
                    reFrame(item: sss)
                }
            }
            
        }
        oriItem.removeFromSuperview()
        success()
    }
    // 移除特定控件
    func removeView(_ item: UIView, success:(()->())) {
        
        if item.isKind(of: FormItem.self) {
            removex(item as! FormItem, success: success)
        } else {
            var lastV: FormItem?
            var index = 0
            while index < self.subviews.count {
                let subV = self.subviews[index]
                if subV != item, subV.isKind(of: FormItem.self) {
                    lastV = subV as? FormItem
                } else {
                    subV.removeFromSuperview()
                    if lastV != nil {
                        reFrame(item: lastV!)
                    }
                    success()
                    break
                }
                index += 1
            }
        }
    }
    // 移除特定控件
    func removex(_ item:FormItem,success:(()->())) {
        
        for subV in self.subviews {
            if subV.isKind(of: FormItem.self) {
                let sss:FormItem = subV as! FormItem
                if sss.nextV == item {
                     if self.tail == item {
                        self.tail = sss
                        sss.nextV = nil
                    } else {
                        sss.nextV = item.nextV
                    }
                    item.nextV = nil
                    reFrame(item: sss)
                }
            }
         }
        
        item.removeFromSuperview()
        success()
    }
    // 移除特定多个控件
    func removex(_ items:[FormItem],success:(()->())) {
        
        for subV in self.subviews {
            if subV.isKind(of: FormItem.self) {
                let sss:FormItem = subV as! FormItem
                
                 for rItem in items {
                    if sss.nextV == rItem {
                        
                        KSLog("在\(sss.tagx.unwrap)后面移除\(rItem.tagx.unwrap)---------")

                         if self.tail == rItem {
                            self.tail = sss
                            sss.nextV = nil
                        } else {
                            sss.nextV = rItem.nextV
                        }
                        rItem.nextV = nil
                     }
                }
 
            }
         }
        reFrame(item: self.head!)
        for rItem in items {
            rItem.removeFromSuperview()
        }
          success()
    }
 
    
    // 移除特定控件之后的所有控件
    func removeFrom(_ item:FormItem,success:(()->())) {
        
        self.tail = item
        removeNext(item)
        reFrame(item: item)
        success()
         // 单纯移除下一个控件，不处理UI
        func removeNext(_ item:FormItem) {
             if item.nextV.isSome {
                removeNext(item.nextV!)
                 item.nextV!.removeFromSuperview()
            }
        }
    }
    
   
    //整个表单设为不可 编辑
    func disableForm() {
        for subs in self.subviews {
            if subs.isKind(of: KSFormBaseItem.self) {
                (subs as! KSFormBaseItem).disabled = true
            }
        }
    }
    
    // 连续添加formitem 控件
    @discardableResult
    func add(_ item:KSFormBaseItem) -> FormView {
        var currY:CGFloat = 0
        if self.tail.isNone { // 没尾 肯定是第一个
            self.head = item
            self.tail = item
        } else {
            currY = self.tail!.frame.maxY
            self.tail!.nextV = item
        }
        
        
        self.addSubview(item)
        let hhh = getHeightFromItem(item:item,appearance: item.appearance, type: item.getNowType())
      
        
        
        item.frame = CGRect(x: 0, y:currY, width: self.ks_width, height: hhh)
        
        self.tail = item
        self.ks_height = item.frame.maxY
        return self
    }
    
    // 连续添加formitem 控件  items 控件组   widths  宽度组，没传就默认均宽
    @discardableResult
    func addItems(items:[KSFormHItem],widths:[CGFloat]? = nil) -> FormView {
        var currY:CGFloat = 0
        if self.tail.isNone { // 没尾 肯定是第一个
            self.tail = items.first
        } else {
            currY = self.tail!.frame.maxY
            self.tail!.nextV = items.first
        }
        if widths.isSome {
            var lastL:CGFloat = 1
            for i in 0..<items.count {
                let oneItem = items[i]
                self.addSubview(oneItem)
                let hhh = getHeightFromItem(item:oneItem,appearance: oneItem.appearance, type: items[i].getNowType())
                oneItem.frame = CGRect(x: lastL, y:currY, width: widths![i], height: hhh)
                lastL += widths![i]
            }

        } else {
            let ww = (self.ks_width - CGFloat(items.count)) / CGFloat(items.count)
            for i in 0..<items.count {
                let oneItem = items[i]
                self.addSubview(oneItem)
                let hhh = getHeightFromItem(item:oneItem,appearance: oneItem.appearance, type: oneItem.getNowType())
                oneItem.frame = CGRect(x: 1 + ww * CGFloat(i), y:currY, width: ww, height: hhh)
            }
        }
        
        self.tail = items.first
        self.ks_height = items.first!.frame.maxY
        return self
    }
    
    func removeAllItem() {
        for item in self.subviews {
            item.removeFromSuperview()
        }
        self.ks_height = 0
        self.tail = nil
    }
    
    // 连续添加UIButton 控件
    @discardableResult
    func add(_ btn:KSUIButton) -> FormView {
        var currY:CGFloat = 0
        if self.tail.isNone { // 没尾 肯定是第一个
            self.tail = btn
        } else {
            currY = self.tail!.frame.maxY
            self.tail!.nextV = btn
        }
        
        btn.frame = CGRect(x: 0, y: currY, width: self.ks_width, height: ItemBtnHeight)
        self.addSubview(btn)
        
        
        self.tail = btn
        self.ks_height = btn.frame.maxY
        return self
    }
    // 连续添加uiview控件
    @discardableResult
    func addv(view:FormItem) -> FormView {
        self.addSubview(view)
        self.tail!.nextV = view
        self.tail = view
        self.ks_height = view.frame.maxY
        return self
    }
    // 添加间隔
    @discardableResult
    func addSeparate(_ height:CGFloat = SeparateHeight) -> FormView {
        let v = FormItem(frame:CGRect(x: 0, y: self.tail!.frame.maxY, width: self.ks_width, height: height))
        v.backgroundColor = .clear
        v.setLineHidden(true)
        self.addSubview(v)
        
        self.tail!.nextV = v
        self.tail = v
        self.ks_height = v.frame.maxY
        return self
    }
    // 添加分区
    @discardableResult
    func addSection(_ section:ItemSectionView? = nil,titlex:String? = nil) -> FormView {
        var secView = section
        if secView == nil {
            secView = ItemSectionView()
            secView!.lab.text =  titlex
            secView!.btn.isHidden = true
        }
        
        var currY:CGFloat = 0
        if self.tail.isNone { // 没尾 肯定是第一个
            self.tail = secView!
        } else {
            currY = self.tail!.frame.maxY
            self.tail!.nextV = secView!
        }
        
        
        
        secView!.frame = CGRect(x: 0, y: currY, width: self.ks_width, height: 30)
        self.addSubview(secView!)
        
        
        self.tail!.nextV = secView!
        self.tail = secView!
        self.ks_height = secView!.frame.maxY
        
        return self
    }

}
class FormItem:UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(lineV)
        lineV.snp.makeConstraints { make in
            make.left.equalTo(self).offset(8)
            make.right.equalTo(self).offset(-8)
            make.height.equalTo(0.8)
            make.top.equalTo(self)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var lineV:UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(kshex:"#e5e5e5")
        return v
    }()
    func setLineHidden(_ flag:Bool) {
        lineV.isHidden = flag
    }
    var tagx:String?

    var nextV: FormItem?

    lazy var roundTopLeft:CornerView = {
        let v = CornerView(width: ItemCornerRadius, outColor: Theme.awModuleBgColor, innerColor: .white, type: .leftTop)
        
        v.frame = CGRect(x: 0, y: 0, width: ItemCornerRadius, height: ItemCornerRadius )
          v.isHidden = true
         return v
    }()
    lazy var roundTopRight:CornerView = {
        let v = CornerView(width: ItemCornerRadius, outColor: Theme.awModuleBgColor, innerColor: .white, type: .rightTop)
         v.frame = CGRect(x: self.ks_width - ItemCornerRadius, y: 0, width: ItemCornerRadius, height: ItemCornerRadius)
          v.isHidden = true
         return v
    }()
    lazy var roundBottomRight:CornerView = {
        let v = CornerView(width: ItemCornerRadius, outColor: Theme.awModuleBgColor, innerColor: .white, type: .rightBottom)
//        v.frame = CGRect(x: self.ks_width - ItemCornerRadius, y: self.ks_height - ItemCornerRadius, width: ItemCornerRadius, height: ItemCornerRadius)
   
        v.isHidden = true
         return v
    }()
    // 手动切单独圆角，这样cell动态时不会变形，内涵UIBezierPath方法
    lazy var roundBottomLeft:CornerView = {
        let v = CornerView(width: ItemCornerRadius, outColor: Theme.awModuleBgColor, innerColor: .white, type: .leftBottom)
//        v.frame = CGRect(x: 0, y: self.ks_height - ItemCornerRadius, width: ItemCornerRadius, height: ItemCornerRadius)
        v.isHidden = true
         return v
    }()
    func setRoundType(type:KSRoundType,outColor:UIColor? = nil,innerColor:UIColor?  = nil) {
        roundTopLeft.isHidden = true
        roundTopRight.isHidden = true
        roundBottomLeft.isHidden = true
        roundBottomRight.isHidden = true
        if roundTopLeft.superview.isNone {
            self.addSubview(roundTopLeft)
        }
         self.bringSubviewToFront(roundTopLeft)
       
        if roundTopRight.superview.isNone {
        self.addSubview(roundTopRight)
        }
         self.bringSubviewToFront(roundTopRight)
       
        if roundBottomRight.superview.isNone {
        self.addSubview(roundBottomRight)
            roundBottomRight.snp.makeConstraints { make in
                make.width.height.equalTo(ItemCornerRadius)
                make.right.bottom.equalToSuperview()
            }
        }
         self.bringSubviewToFront(roundBottomRight)
         
        if roundBottomLeft.superview.isNone {
        self.addSubview(roundBottomLeft)
            roundBottomLeft.snp.makeConstraints { make in
                make.width.height.equalTo(ItemCornerRadius)
                make.left.bottom.equalToSuperview()
            }
        }
         self.bringSubviewToFront(roundBottomLeft)
        if outColor.isSome && innerColor.isSome {
            roundTopLeft.resetColor(outColor: outColor!, innerColor: innerColor!)
            roundTopRight.resetColor(outColor: outColor!, innerColor: innerColor!)
            roundBottomLeft.resetColor(outColor: outColor!, innerColor: innerColor!)
            roundBottomRight.resetColor(outColor: outColor!, innerColor: innerColor!)

            
        }
        
        if type == .all {
            roundTopLeft.isHidden = false
            roundTopRight.isHidden = false
            roundBottomLeft.isHidden = false
            roundBottomRight.isHidden = false
        } else if type == .top {
            roundTopLeft.isHidden = false
            roundTopRight.isHidden = false
          } else if type == .bottom {
            roundBottomLeft.isHidden = false
            roundBottomRight.isHidden = false
        }
    }
}
// 底部圆角效果view，放在tablefooterview的最上面
let footerRoundRadius:CGFloat = 8
class FootRoundView:UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 初始布局
        self.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: footerRoundRadius)

        self.layer.masksToBounds = true
        self.backgroundColor = .clear
        // 圆角效果
        let footRound = UIView(frame: CGRect(x: 6, y: -8, width: KSGlobal.screenW - 12, height: footerRoundRadius * 2))
        footRound.layer.cornerRadius = footerRoundRadius
        footRound.backgroundColor = .white
        
        let footRoundBG = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: footerRoundRadius))
        footRoundBG.backgroundColor = Theme.commonBg
        footRoundBG.layer.masksToBounds = true
        footRoundBG.addSubview(footRound)
        self.addSubview(footRoundBG)
    }
    func addSubV(subv:UIView) {
        
        self.addSubview(subv)
        self.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: footerRoundRadius + subv.ks_height)
        subv.frame = CGRect(x: 0, y: footerRoundRadius, width: subv.ks_width, height:  subv.ks_height)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
